package com.shine.chemicalWholeProcessSystem.ui.riskAssessment;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.impl.BottomListPopupView;
import com.lxj.xpopup.interfaces.OnCancelListener;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.shine.chemicalWholeProcessSystem.BR;
import com.shine.chemicalWholeProcessSystem.R;
import com.shine.chemicalWholeProcessSystem.app.ChooseData;
import com.shine.chemicalWholeProcessSystem.app.Constants;
import com.shine.chemicalWholeProcessSystem.base.BaseActivity;
import com.shine.chemicalWholeProcessSystem.bean.RiskManagementBean;
import com.shine.chemicalWholeProcessSystem.databinding.ActivityRiskAssessmentListBinding;
import com.shine.chemicalWholeProcessSystem.http.ApiException;
import com.shine.chemicalWholeProcessSystem.http.BaseReturn;
import com.shine.chemicalWholeProcessSystem.http.ECHttpResponse;
import com.shine.chemicalWholeProcessSystem.http.ECObserver;
import com.shine.chemicalWholeProcessSystem.http.RetrofitClient;
import com.shine.chemicalWholeProcessSystem.http.RxUtils;
import com.shine.chemicalWholeProcessSystem.http.Service;
import com.shine.chemicalWholeProcessSystem.ui.adapter.RiskAssessmentListAdapter;
import com.shine.chemicalWholeProcessSystem.view.pop.RiskManagementSearchPopup;

import java.util.ArrayList;
import java.util.List;

import cn.bingoogolapple.baseadapter.BGADivider;
import cn.bingoogolapple.baseadapter.BGAOnItemChildClickListener;
import cn.bingoogolapple.baseadapter.BGAOnRVItemClickListener;

public class RiskAssessmentListActivity extends BaseActivity<ActivityRiskAssessmentListBinding, RiskAssessmentListViewModel> {
    private final int REFRESH = 1000;
    private RiskAssessmentListAdapter riskAssessmentListAdapter;
    private boolean isChooseMore = false;
    private BottomListPopupView xPopup;
    private String riskClassificationStr, riskName, riskNumber;
    private int riskClassificationPosition = -1;
    private List<RiskManagementBean> dataList = new ArrayList<>();

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_risk_assessment_list;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public RiskAssessmentListViewModel initViewModel() {
        return new RiskAssessmentListViewModel(this);
    }

    @Override
    public int appTheme() {
        return Constants.THEME_FULL;
    }

    @Override
    public void initData() {
        super.initData();
        setStatusBar();
        initTitle(this, "风险研判");

        binding.refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                binding.refreshLayout.finishRefresh(1000);
                binding.refreshLayout.setEnableLoadMore(true);

                refresh();
            }
        });
        binding.refreshLayout.setEnableLoadMore(false);
//        binding.refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
//            @Override
//            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
//                binding.refreshLayout.finishLoadMore(1000);
//                page++;
//                getSensorHisAlarm();
//            }
//        });

        riskAssessmentListAdapter = new RiskAssessmentListAdapter(binding.recyclerView, R.layout.item_ra_list);
        binding.recyclerView.setAdapter(riskAssessmentListAdapter);
        binding.recyclerView.addItemDecoration(BGADivider.newBitmapDivider());
        binding.recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                if (RecyclerView.SCROLL_STATE_DRAGGING == newState) {
                    riskAssessmentListAdapter.closeOpenedSwipeItemLayoutWithAnim();
                }
            }
        });

        riskAssessmentListAdapter.setOnRVItemClickListener(new BGAOnRVItemClickListener() {
            @Override
            public void onRVItemClick(ViewGroup parent, View itemView, int position) {
                if (isChooseMore) {
                    dataList.get(position).setChoose(!dataList.get(position).isChoose());
                    riskAssessmentListAdapter.notifyDataSetChanged();
                } else {
                    Bundle bundle = new Bundle();
                    bundle.putSerializable(Constants.BUNDLE_EXTRA, dataList.get(position));
                    switchActivityForResult(RiskAssessmentDetailsActivity.class, REFRESH, bundle);
                }
            }
        });


        riskAssessmentListAdapter.setOnItemChildClickListener(new BGAOnItemChildClickListener() {
            @Override
            public void onItemChildClick(ViewGroup parent, View childView, int position) {
                if (childView.getId() == R.id.tv_item_bgaswipe_edit) {
                    Bundle bundle = new Bundle();
                    bundle.putBoolean(Constants.BUNDLE_EDIT, true);
                    bundle.putSerializable(Constants.BUNDLE_EXTRA, dataList.get(position));
                    switchActivityForResult(RiskAssessmentCreateActivity.class, REFRESH, bundle);
                }
                if (childView.getId() == R.id.tv_item_bgaswipe_delete) {
                    riskAssessmentListAdapter.closeOpenedSwipeItemLayoutWithAnim();
                    new XPopup.Builder(RiskAssessmentListActivity.this)
                            .isDestroyOnDismiss(true)
                            .asConfirm("提示", "确认要删除这条数据", new OnConfirmListener() {
                                @Override
                                public void onConfirm() {
                                    delDangerousPoint(dataList.get(position).getId());
                                }
                            })
                            .show();
                }
            }
        });

        binding.riskClassification.setOnClickListener(this);
        binding.search.setOnClickListener(this);

        binding.addText.setOnClickListener(this);
        binding.editText.setOnClickListener(this);
        binding.deleteText.setOnClickListener(this);
        binding.cancelText.setOnClickListener(this);

        dataList.add(new RiskManagementBean());
        dataList.add(new RiskManagementBean());
        dataList.add(new RiskManagementBean());

        riskAssessmentListAdapter.addNewData(dataList);

//        getDangerousPoint();
    }


    private void getDangerousPoint() {
        showLoading("");
        RetrofitClient.getInstance().create(Service.class)
                .GetDangerousPoint()
                .compose(RxUtils.<ECHttpResponse<List<RiskManagementBean>>>bindToLifecycle(this))
                .compose(RxUtils.<ECHttpResponse<List<RiskManagementBean>>>schedulersTransformer())
                .compose(RxUtils.<ECHttpResponse<List<RiskManagementBean>>>exceptionTransformer())
                .subscribe(new ECObserver<List<RiskManagementBean>>() {
                    @Override
                    protected void _onNext(List<RiskManagementBean> riskManagementBeanList) {
                        dismissLoading();
                        dataList.addAll(riskManagementBeanList);
                        riskAssessmentListAdapter.addNewData(dataList);
                    }

                    @Override
                    protected void _onError(ApiException ex) {
                        ToastMessage(ex.message);
                        dismissLoading();
                    }
                });
    }

    private void delDangerousPoint(String id) {
        showLoading("");
        RetrofitClient.getInstance().create(Service.class)
                .DelDangerousPoint(id)
                .compose(RxUtils.<ECHttpResponse<BaseReturn>>bindToLifecycle(this))
                .compose(RxUtils.<ECHttpResponse<BaseReturn>>schedulersTransformer())
                .compose(RxUtils.<ECHttpResponse<BaseReturn>>exceptionTransformer())
                .subscribe(new ECObserver<BaseReturn>() {
                    @Override
                    protected void _onNext(BaseReturn baseReturn) {
                        dismissLoading();
                        ToastMessage("删除成功");
                        cancelChooseMore();

                        refresh();
                    }

                    @Override
                    protected void _onError(ApiException ex) {
                        ToastMessage(ex.message);
                        dismissLoading();
                    }
                });
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.addText:
                switchActivityForResult(RiskAssessmentCreateActivity.class, REFRESH);
                break;
            case R.id.editText:
                if (isChooseMore) {
                    if (getChooseCount() == 1) {
                        Bundle bundle = new Bundle();
                        bundle.putBoolean(Constants.BUNDLE_EDIT, true);
                        bundle.putSerializable(Constants.BUNDLE_EXTRA, getChooseData());
                        switchActivityForResult(RiskAssessmentCreateActivity.class, REFRESH, bundle);
                        cancelChooseMore();
                    } else {
                        ToastMessage("请选择一条数据编辑");
                    }
                } else {
                    isChooseMore = true;
                    riskAssessmentListAdapter.setChooseMore(isChooseMore);
                    riskAssessmentListAdapter.notifyDataSetChanged();
                    binding.cancelText.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.deleteText:
                if (isChooseMore) {
                    System.out.println(getChooseCount());
                    if (getChooseCount() > 0) {
                        isChooseMore = false;
                        new XPopup.Builder(RiskAssessmentListActivity.this)
                                .isDestroyOnDismiss(true)
                                .asConfirm("提示", "确认要删除" + getChooseCount() + "条数据", new OnConfirmListener() {
                                    @Override
                                    public void onConfirm() {
                                        ToastMessage("删除成功");
                                        cancelChooseMore();
                                    }
                                })
                                .show();
                    }
                } else {
                    isChooseMore = true;
                    riskAssessmentListAdapter.setChooseMore(isChooseMore);
                    riskAssessmentListAdapter.notifyDataSetChanged();
                    binding.cancelText.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.cancelText:
                cancelChooseMore();
                break;
            case R.id.riskClassification:
                String[] data = ChooseData.riskClassificationList().toArray(new String[0]);
                xPopup = (BottomListPopupView) new XPopup.Builder(RiskAssessmentListActivity.this)
                        .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
                        .maxHeight(1000)
                        .autoDismiss(false)
                        .asBottomList("风险分类", data, null, riskClassificationPosition, false,
                                new OnSelectListener() {
                                    @Override
                                    public void onSelect(int position, String text) {
                                        riskClassificationStr = text;
                                        riskClassificationPosition = position;
                                        xPopup.setCheckedPosition(position);
                                    }
                                }, R.layout.item_risk_classification_screen, 0)
                        .show();

                xPopup.getPopupContentView().findViewById(R.id.reset).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        xPopup.dismiss();
                        binding.riskClassification.setText("风险分类");
                        riskClassificationPosition = -1;
                    }
                });

                xPopup.getPopupContentView().findViewById(R.id.search).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        xPopup.dismiss();
                        binding.riskClassification.setText(riskClassificationStr);
                    }
                });
                break;
            case R.id.search:
                RiskManagementSearchPopup riskManagementSearchPopup = new RiskManagementSearchPopup(this);
                new XPopup.Builder(this)
                        .moveUpToKeyboard(true)
                        .enableDrag(true)
                        .isDestroyOnDismiss(true)
                        .asCustom(riskManagementSearchPopup)
                        .show();
                riskManagementSearchPopup.show();
                riskManagementSearchPopup.setListener(new OnConfirmListener() {
                    @Override
                    public void onConfirm() {
                        riskName = riskManagementSearchPopup.getRiskName();
                        riskNumber = riskManagementSearchPopup.getRiskNum();
                    }
                }, new OnCancelListener() {
                    @Override
                    public void onCancel() {

                    }
                });

                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REFRESH:
                    refresh();
                    break;
                default:
                    break;
            }
        }
    }

    private int getChooseCount() {
        int chooseCount = 0;
        for (RiskManagementBean riskManagementBean : dataList) {
            if (riskManagementBean.isChoose())
                chooseCount++;
        }
        return chooseCount;
    }

    private RiskManagementBean getChooseData() {
        for (RiskManagementBean riskManagementBean : dataList) {
            if (riskManagementBean.isChoose())
                return riskManagementBean;
        }
        return null;
    }

    private void clearChoose() {
        for (RiskManagementBean riskManagementBean : dataList) {
            if (riskManagementBean.isChoose())
                riskManagementBean.setChoose(false);
        }
    }

    private void cancelChooseMore() {
        binding.cancelText.setVisibility(View.GONE);
        isChooseMore = false;
        clearChoose();
        riskAssessmentListAdapter.setChooseMore(isChooseMore);
        riskAssessmentListAdapter.notifyDataSetChanged();
    }

    private void refresh() {
        riskAssessmentListAdapter.closeOpenedSwipeItemLayoutWithAnim();
        dataList.clear();
        riskAssessmentListAdapter.clear();
        getDangerousPoint();
    }
}
